package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock{
    //锁的前缀
    private static final String KEY_PREFIX = "lock:";
    private static final String ID_PREFIX = UUID.randomUUID().toString(true)+"-";
    //具体业务名称，将前缀和业务名拼接之后当做Key
    private String name;

    private StringRedisTemplate stringRedisTemplate;
    //释放锁的lua脚本
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT =new DefaultRedisScript<>();//创建脚本对象
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));//设置脚本位置
        UNLOCK_SCRIPT.setResultType(Long.class);//设置返回类型
    }

    public SimpleRedisLock(StringRedisTemplate stringRedisTemplate, String name) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.name = name;
    }


    @Override
    public boolean tryLock(long timeoutSec) {
        //获取线程标识
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        String threadIdString = threadId + " ";
        //获取锁
        Boolean success = stringRedisTemplate.opsForValue().setIfAbsent
                ("KEY_PREFIX" + name, threadIdString, timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success);
    }
    //使用lua脚本释放锁 ->execute
    @Override
    public void unlock() {
        stringRedisTemplate.execute(UNLOCK_SCRIPT,
                Collections.singletonList("KEY_PREFIX" + name),
                ID_PREFIX +Thread.currentThread().getId());
    }


//    @Override
//    public void unlock() {
//        //获取线程标识
//        String threadId = ID_PREFIX+Thread.currentThread().getId();
//        //获取锁的标识
//        String idLock = stringRedisTemplate.opsForValue().get("KEY_PREFIX" + name);
//        //判断标识是否一致
//        if(threadId.equals(idLock)){
//            //释放锁
//            stringRedisTemplate.delete("KEY_PREFIX" + name);
//        }
//
//    }

}
